package com.hue.springbootshiro.config;

import com.hue.springbootshiro.realm.ShiroRealm;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * Shrio的配置:
 * 1.创建Realm
 * 2.配置DefaultWebSecurityManager
 * 3.配置ShiroFilterFactoryBean
 */
@Configuration
public class ShiroConfig {
    //1.创建自定义Realm
    @Bean
    public ShiroRealm shiroRealm() {
        return new ShiroRealm();
    }

    //2.创建DefaultWebSecurityManager
    @Bean
    public DefaultSecurityManager defaultSecurityManager(ShiroRealm shiroRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //设置自定义realm
        securityManager.setRealm(shiroRealm);
        return securityManager;
    }

    //3.创建ShiroFilterFactoryBean
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultSecurityManager defaultSecurityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();

        shiroFilterFactoryBean.setSecurityManager(defaultSecurityManager);

        /**
         * 设置shiro拦截器,指定哪些资源需要什么权限才能访问
         * 常用的过滤器：
         *      1.anon:不需要认证就可以访问
         *      2.authc:必须认证才能访问
         *      3.user:如果使用rememberMe功能可以直接访问
         *      4.perms:该资源必须得到资源权限才能访问
         *      5.roles:该资源必须得到角色权限才能访问
         */
        Map<String,String> map = new HashMap<>();
        map.put("/user/add","perms[user:add]");
        map.put("/user/update","perms[user:update]");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);

        //设置登录页面
        shiroFilterFactoryBean.setLoginUrl("/login");
        //设置未授权时跳转的页面
        shiroFilterFactoryBean.setUnauthorizedUrl("/user/authorized");
        return shiroFilterFactoryBean;
    }
}
